package com.github.authcloud.server.configure;

import com.github.authcloud.server.configure.properties.AuthCommonProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author : zhaoxuan
 * @version : 1.0
 * @date : 2021/8/22 15:01
 * @description : AuthMappingInit
 */
public class AuthMappingCommandLineRunner implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private final Timer timer = new Timer("AuthCloud-AuthRolePermissionMappingTimer", true);

    private final RedisTemplate<String, String> authRedisTemplate;

    private final AuthCommonProperties authCommonProperties;

    public AuthMappingCommandLineRunner(RedisTemplate redisTemplate, AuthCommonProperties authCommonProperties) {
        this.authRedisTemplate = redisTemplate;
        this.authCommonProperties = authCommonProperties;
    }

    @Override
    public void run(String... args) throws Exception {
        listenNoLoginMappingInit();
        listenAuthMappingEvent();
        startTimer();
    }

    private void listenNoLoginMappingInit(){
        logger.info("AuthCloud--synchronize no login mapping info -- start");
        AuthRolePermissionLocalCache.syncNoLoginMappingMapInit(authRedisTemplate);
        logger.info("AuthCloud--synchronize no login mapping info -- end");
    }

    private void listenAuthMappingEvent(){
        logger.info("AuthCloud--synchronize roles and permission mapping info -- start");
        AuthRolePermissionLocalCache.syncRolePermissionMappingMapInit( authRedisTemplate);
        logger.info("AuthCloud--synchronize roles and permission mapping info -- end");
    }

    public void startTimer() {
        int fetch = authCommonProperties.getAuthRolePermissionFetch() * 60 * 1000;
        int fetchDelay = authCommonProperties.getFetchDelay() * 60 * 1000;
        if (fetch > 0) {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        listenNoLoginMappingInit();
                        listenAuthMappingEvent();
                    } catch (Throwable e) {
                        logger.error("AuthCloud--Cannot timing synchronize no login role permission mapping", e);
                    }
                }
            }, fetchDelay, fetch);
        }
    }

}
